package com.csdj.wenjun.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.csdj.wenjun.common.CacheConstant;
import com.csdj.wenjun.common.StatusContant;
import com.csdj.wenjun.common.WebResult;
import com.csdj.wenjun.entity.*;
import com.csdj.wenjun.service.*;
import com.csdj.wenjun.utils.TuPianJianChai;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wenjun
 * @since 2022-01-10
 */
@RestController
@RequestMapping("/manhe")
public class ManheController {
    @Autowired
    private ManheService manheService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private PtsuipianService ptsuipianService;
    @Autowired
    private UserService userService;
    @Autowired
    private SuipianjiluService suipianjiluService;
    @Autowired
    private JifenjiluService jifenjiluService;
    @GetMapping("/huodeshuzhu")
    public WebResult huodeshuzhu(@RequestParam int[] num,@RequestParam String manheid,@RequestParam String userid
            ,@RequestParam int jifen){
        int result=grabBuy(manheid,num.length);
        if(result>0){
            for(int i=0;i<num.length;i++){
                Suipianjilu suipianjilu=new Suipianjilu();
                suipianjilu.setManheid(Integer.parseInt(manheid));
                suipianjilu.setPtid(Integer.parseInt(manheid));
                suipianjilu.setSpweizhi(num[i]);
                suipianjilu.setUserid(Integer.parseInt(userid));
                suipianjiluService.save(suipianjilu);
            }
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", userid);
            updateWrapper.set("jifen",jifen);
            QueryWrapper<User> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.lambda().eq(User::getId,userid);
            User user2=userService.getOne(queryWrapper1);
            Jifenjilu jifenjilu1=new Jifenjilu();
            jifenjilu1.setShuliang(-(user2.getJifen()-jifen));
            jifenjilu1.setType("盲盒抽奖");
            jifenjilu1.setUserid(user2.getId());
            jifenjilu1.setYujifen(jifen);
            jifenjiluService.save(jifenjilu1);
            if(userService.update(updateWrapper)){
                System.out.println("扣去积分成功");
            }else {
                System.out.println("扣去积分失败");
            }
        }else {
            return new WebResult(StatusContant.USER_STATUS_LOCKED);
        }
        return new WebResult(StatusContant.USER_STATUS_OK,result);
    }
    @GetMapping("/jianjietupian")
    public String jianjietupian(@RequestParam String url,@RequestParam int manheid){
        TuPianJianChai.jianJie(url);
        for(int i=0;i<9;i++){
            Ptsuipian ptsuipian=new Ptsuipian();
            ptsuipian.setManheid(manheid);
            ptsuipian.setUrl(url.replace(".", "_small"+(i+1)+"."));
            ptsuipian.setSpweizhi(i+1);
            ptsuipianService.save(ptsuipian);
        }
        //初始化实际卖出的商品数量0
        return "Ok";
    }
    @GetMapping("/selecthc")
    public Manhe selecthc(@RequestParam int manheid){
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        //初始化实际卖出的商品数量0
        Manhe manhe=(Manhe)redisTemplate.opsForValue().get(CacheConstant.MANHE+manheid);
        if(manhe==null){
            QueryWrapper<Manhe> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(Manhe::getId,manheid);
            return manheService.getOne(queryWrapper);
        }
        return manhe;
    }
    // 设置库存
    @GetMapping("/setStockNum")
    public String setStockNum(@RequestParam Integer manheid){
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        QueryWrapper<Manhe> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Manhe::getId,manheid);
        Manhe manhe=manheService.getOne(queryWrapper);
        redisTemplate.opsForValue().set(CacheConstant.MANHE+manheid,manhe);
        return "Ok";
    }
    @GetMapping("/grabBuy")
    public int grabBuy(String manheid,int num) {
        //修改key的序列化类型 提高可读行 StringRedisSerializer设置key的类型为string
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        RLock rLock = redissonClient.getLock("product");
        try {
            rLock.lock();
//            redisTemplate.opsForSet().pop()
            Manhe manhe = (Manhe)redisTemplate.opsForValue().get(CacheConstant.MANHE+manheid);
            if (manhe.getKecount() < 1) {
                return 0;
            }
            // 自减一
            int shuliang=manhe.getKecount();
            manhe.setKecount(shuliang-num);
            redisTemplate.opsForValue().set(CacheConstant.MANHE+manheid,manhe);
            System.out.println(manhe.getKecount());
            return  manhe.getKecount();
        } finally {
            rLock.unlock();
        }
    }

    @ResponseBody
    @GetMapping("/selectptsuipian")
    public List selectptsuipian(@RequestParam int manheid){
        QueryWrapper<Ptsuipian> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Ptsuipian::getManheid,manheid);
        return ptsuipianService.list(queryWrapper);
    }

    @GetMapping("/selectmanhe")
    public List selectuserid(){
        return manheService.list();
    }
    @GetMapping("/selectmanheid")
    public Manhe selectmanheid(@RequestParam String id){
        QueryWrapper<Manhe> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Manhe::getId,id);
        return manheService.getOne(queryWrapper);
    }

    /**
     * 高并发问题
     * @param
     * @return
     */
//    @ResponseBody
//    @GetMapping("/selectClearShuliang")
//    public int findUserByName( ){
//
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(grabBuy("1"));
//            }
//        };
//        ExecutorService executorService = Executors.newFixedThreadPool(25);
//        for (int i = 0; i < 10000; i++) {
//            executorService.submit(runnable);
//        }
//
//        return 1;
//    }
}
